package co.yixiang.common.util;

import co.yixiang.common.bean.LocalCache;
import co.yixiang.modules.distributor.domain.YxDistributor;
import co.yixiang.modules.distributor.service.YxDistributorService;
import co.yixiang.modules.distributor.service.dto.YxDistributorQueryCriteria;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class GlobalCache {

    private static Timer timer = new Timer(true);

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final YxDistributorService distributorService;

    public GlobalCache(YxDistributorService distributorService) {
        this.distributorService = distributorService;
    }

    @PostConstruct
    public void init() {
        initCache();
        //refresh();
    }

    private void initCache() {
        try {
            Map<String, YxDistributor> distributorTelMap = new ConcurrentHashMap<>();
            List<YxDistributor> yxDistributors = distributorService.queryAll(new YxDistributorQueryCriteria());
            for (YxDistributor yxDistributor : yxDistributors) {
                if (!Strings.isNullOrEmpty(yxDistributor.getLinkTel())) {
                    String[] tels = yxDistributor.getLinkTel().split(",");
                    for (String tel : tels) {
                        distributorTelMap.put(tel, yxDistributor);
                    }
                }
            }

            LocalCache.distributorTelMap = distributorTelMap;
        } catch (Exception e) {
            logger.error("init distributorTelMap error", e);
        }
    }


    //60s刷新一次缓存
    private void refresh() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                initCache();
            }
        }, 10 * 1000L, 60 * 1000L);
    }
}
